package com.mchat.communication.process.message;

import com.mchat.communication.process.message.impl.*;
import com.mchat.communication.protocol.IMMessage;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Component
public class MsgProcessorFactory {
    private final Map<MessageType, MessageProcessor> processors = new HashMap<>();
    @Resource
    private DocMsgProcessor docMsgProcessor;
    @Resource
    private TextMsgProcessor textMsgProcessor;
    @Resource
    private FileMsgProcessor fileMsgProcessor;
    @Resource
    private ImageMsgProcessor imageMsgProcessor;
    @Resource
    private LinkMsgProcessor linkMsgProcessor;
    @Resource
    private LoginMsgProcessor loginMsgProcessor;
    @Resource
    private LogoutMsgProcessor logoutMsgProcessor;

    public MessageProcessor getProcessor() {
        return getProcessor(MessageType.TEXT);
    }

    public MessageProcessor getProcessor(MessageType type) {
        if (MessageType.FILE.equals(type)) {
            return processors.computeIfAbsent(type, name -> fileMsgProcessor);
        } else if (MessageType.DOC.equals(type)) {
            return processors.computeIfAbsent(type, name -> docMsgProcessor);
        } else if (MessageType.LINK.equals(type)) {
            return processors.computeIfAbsent(type, name -> linkMsgProcessor);
        } else if (MessageType.LOGIN.equals(type)) {
            return processors.computeIfAbsent(type, name -> loginMsgProcessor);
        } else if (MessageType.LOGOUT.equals(type)) {
            return processors.computeIfAbsent(type, name -> logoutMsgProcessor);
        } else if (MessageType.IMAGE.equals(type)) {
            return processors.computeIfAbsent(type, name -> imageMsgProcessor);
        }
        return processors.computeIfAbsent(type, name -> textMsgProcessor);
    }

    public MessageProcessor getProcessor(IMMessage msg) {
        MessageType type = MessageType.valueOf(msg.getAction());
        return getProcessor(type);
    }
}
